package com.hh.tc.ui.main

import android.os.Build
import android.view.View
import androidx.annotation.RequiresApi
import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableField
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.SavedStateHandle
import com.hh.base.log.Logger
import com.hh.base.ui.BaseViewModel
import com.hh.base.ui.bridge.Event
import com.hh.base.util.ext.DateType
import com.hh.base.util.ext.getRemainingDaysInMonth
import com.hh.base.util.ext.toJsonString
import com.hh.base.util.ext.toShow
import com.hh.base.widget.dialog.MultifunctionDialog
import com.hh.base.widget.pickerview.listener.OnTimeSelectListener
import com.hh.db.core.ObjectBoxUtil
import com.hh.db.core.ObjectBoxUtil.queryFirst
import com.hh.db.core.ObjectBoxUtil.queryList
import com.hh.db.entity.ClockInRecord
import com.hh.db.entity.ClockInRecord_
import com.hh.db.entity.ClockMonth
import com.hh.db.entity.ClockMonth_
import com.hh.tc.entity.MyOption
import com.hh.tc.ui.clockIn.monthList.MonthListActivity
import java.util.Date
import java.util.Timer
import java.util.TimerTask

/**
 * Create By hHui on 2025/4/3 13:35
 *
 * @description
 */
class MainViewModel(handle: SavedStateHandle) : BaseViewModel(handle) {
    val options = ObservableArrayList<MyOption>()
    val clockInButtonVisible = ObservableField(View.GONE)
    val clockInButtonText = ObservableField("")
    val clockInButtonBackgroundColor = ObservableField("#009432")
    private var timer: Timer? = null
    private var task: TimerTask? = null
    private val _drawerState = MutableLiveData<Event<DrawerState>>(Event(DrawerState.Closed))
    val drawerState: LiveData<Event<DrawerState>> = _drawerState

    init {
        val list = ArrayList<MyOption>()
        list.add(MyOption("打卡记录", MonthListActivity::class.java))

        options.addAll(list)
    }

    fun onItemClick(option: MyOption) {
        Logger.dft().v(TAG, "点击 ${option.toJsonString()}")
        jump2Activity(option.target, false)
    }

    fun settingClick() {
        _drawerState.value = Event(DrawerState.Open)
    }

    private fun startKeepTime(isBegin: Boolean) {
        if (timer == null) {
            timer = Timer()
        }
        task?.let {
            task?.cancel()
            task = null
        }
        task = object : TimerTask() {
            override fun run() {
                val date = Date().toShow(DateType.H_M_S)
                if (isBegin) {
                    clockInButtonText.set("${date}\n上班打卡")
                } else {
                    clockInButtonText.set("${date}\n下班打卡")
                }
            }
        }
        timer?.schedule(task, 0, 1000)
    }

    private fun stopKeepTime() {
        timer?.let {
            timer = null
        }
        task?.cancel()
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun initData() {
        createMothData()
    }


    fun clockIn() {
        ObjectBoxUtil.clockInRecordBox.queryFirst(ClockInRecord_.date.equal(Date().toShow(DateType.DAY))).let { record ->
            record?.let {
                if (it.begin == null) {
                    it.begin = Date().toShow()
                    clockInButtonBackgroundColor.set("#ea2027")
                    startKeepTime(false)
                } else if (it.end == null) {
                    it.end = Date().toShow()
                    stopKeepTime()
                    clockInButtonVisible.set(View.GONE)
                }
                ObjectBoxUtil.clockInRecordBox.put(it)
            }
        }
    }

    fun clearData() {
        alertOption(msg = "确定清除所有数据？", clickListener = object : MultifunctionDialog.AlertClickListener {
            override fun onConfirm(content: String?) {
                ObjectBoxUtil.clear()
            }

            override fun onCancel() {
            }
        })
    }

    fun test() {
        showDateTimerPicker({ date, v ->
            showToast(date.toShow())
        })
    }

    /**
     * 创建本月的数据
     */
    @RequiresApi(Build.VERSION_CODES.O)
    private fun createMothData() {
        //创建月度打卡记录
        val monthStr = Date().toShow(DateType.MONTH)
        ObjectBoxUtil.clockMonthBox.queryFirst(ClockMonth_.month.equal(monthStr)).let {
            if (it == null) {
                val item = ClockMonth()
                ObjectBoxUtil.clockMonthBox.put(item)
            }
        }
        //创建本月剩余日期的打卡记录
        ObjectBoxUtil.clockInRecordBox.queryList(ClockInRecord_.month.equal(monthStr)).let { result ->
            if (result.isEmpty()) {
                val list = Date().getRemainingDaysInMonth()
                Logger.dft().v(TAG, "剩余日期 ${list.toJsonString()}")
                val list1 = ArrayList<ClockInRecord>()
                list.forEach {
                    val record = ClockInRecord()
                    record.month = monthStr
                    record.date = it
                    list1.add(record)
                }
                ObjectBoxUtil.clockInRecordBox.put(list1)
            }
        }
    }

    override fun onPause(owner: LifecycleOwner) {
        super.onPause(owner)
        stopKeepTime()
    }

    override fun onStart(owner: LifecycleOwner) {
        super.onStart(owner)
        ObjectBoxUtil.clockInRecordBox.queryFirst(ClockInRecord_.date.equal(Date().toShow(DateType.DAY))).let { record ->
            if (record == null) {
                val record1 = ClockInRecord()
                ObjectBoxUtil.clockInRecordBox.put(record1)
                clockInButtonVisible.set(View.VISIBLE)
                startKeepTime(true)
            } else {
                if (record.begin == null) {
                    clockInButtonVisible.set(View.VISIBLE)
                    startKeepTime(true)
                } else if (record.end == null) {
                    clockInButtonVisible.set(View.VISIBLE)
                    clockInButtonBackgroundColor.set("#ea2027")
                    startKeepTime(false)
                }
            }
        }
    }

    sealed class DrawerState {
        object Open : DrawerState()
        object Closed : DrawerState()
    }
}